package main.java.easy;
import main.java.structure.ListNode;
/**
 * @Author: 郑国荣
 * @Date: 2023-07-10-10:54
 * @Description: 合并两个有序队列
 */
public class MergeTwoLists {

    public static void main(String[] args) {
        // 创建测试用例
        ListNode list1 = new ListNode(1);
        list1.next = new ListNode(3);
        list1.next.next = new ListNode(5);

        ListNode list2 = new ListNode(2);
        list2.next = new ListNode(4);
        list2.next.next = new ListNode(6);

        // 调用 mergeTwoLists 方法合并两个链表
//        ListNode mergedList = mergeTwoLists(list1, list2);
        ListNode mergedList = mergeTwoListByIteration(list1, list2);

        // 打印合并后的链表结果
        while (mergedList != null) {
            System.out.print(mergedList.val + " ");
            mergedList = mergedList.next;
        }
        System.out.println();
    }

    public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null)
            return list2;
        if (list2 == null)
            return list1;

        if (list1.val < list2.val) {
            list1.next = mergeTwoLists(list1.next, list2);
            return list1;
        } else {
            list2.next = mergeTwoLists(list2.next, list1);
            return list2;
        }
    }

    //迭代算法
    public static ListNode mergeTwoListByIteration(ListNode l1,ListNode l2){
        ListNode dumpHead = new ListNode(0);
        ListNode dumpList = dumpHead;
        while (l1 != null && l2 != null){
            if (l1.val < l2.val){
                dumpList.next = l1;
                l1 = l1.next;
            }
            else {
                dumpList.next = l2;
                l2 = l2.next;
            }
            dumpList = dumpList.next;
        }

        if (l1 == null){
            dumpList.next = l2;
        }
        if (l2 == null){
            dumpList.next = l1;
        }
        return dumpHead.next;
    }

}

